﻿using ECGConversion;
using ECGConversion.ECGLeadMeasurements;
using ECGConversion.ECGSignals;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HnECGConverter2
{
    public partial class ProgressFrm : Form
    {
        public ProgressFrm(string[] args)
        {
            
            InitializeComponent();
            if (args.Length == 0)
            {
                string path = "temp.json";
                var jsontmpre = JsonHelper.DeserializeFileToObject<JsonFormat>(path);
                string src = "temp.json";
                string dst = "temp.xml";
                try
                {
                    IECGFormat CurrentECG = null;
                    UnknownECGReader _ECGReader = null;
                    if(new FileInfo(src).Exists)
                    {
                        int index = 0;
                        if (_ECGReader == null)
                        {
                            _ECGReader = new UnknownECGReader();
                        }
                        CurrentECG = _ECGReader.Read("Example.xml");
                        int leadCount = jsontmpre.ChDatas.Count;
                        Signal[] _sign = new Signal[leadCount];
                        for (int i = 0; i < leadCount; i++)
                        {
                            _sign[i] = new Signal();
                            try
                            {
                                string leadname = jsontmpre.ChDatas[i].LeadName.Trim();// I、II、III……
                                // 导联类型
                                _sign[i].Type = (LeadType)(LeadType)ECGConverter.EnumParse(
                                     typeof(LeadType), leadname, true);
                                //导联数据 ，
                                string[] datastr = jsontmpre.ChDatas[i].digital.TrimEnd().Split(' ');
                                short[] shortArray = Array.ConvertAll<string, short>(datastr, delegate (string s) { return (short)(float.Parse(s) * 1000); });//.Skip(1).Take(5000).ToArray();
                                _sign[i].Rhythm = (short[])shortArray.Clone();
                                _sign[i].RhythmStart = 0;
                                _sign[i].RhythmEnd = shortArray.Length - 1;
                            }
                            catch (Exception e)
                            {
                                throw e;
                            }
                        }

                        Signals signals = new Signals();
                        CurrentECG.Signals.getSignals(out signals);

                        //采样率
                        signals.RhythmSamplesPerSecond = int.Parse(jsontmpre.Increament);
                        //增益 
                        signals.MedianAVM = int.Parse(jsontmpre.ChDatas[1].Sacle);
                        //signals.RhythmAVM = int.Parse(jsontmpre.array_obj[1].Sacle);
                        signals.SetLeads(_sign);
                        //CurrentECG.Signals.getSignals(out signals);
                        CurrentECG.Signals.setSignals(signals);




                        //在这里设置参数信息 
                        //setLeadMeasurements
                        //设置导联参数 
                        LeadMeasurements leadMeasurements;
                        //CurrentECG.LeadMeasurements.getLeadMeasurements(out leadMeasurements);
                        //这里补充参数
                        //CurrentECG.LeadMeasurements.setLeadMeasurements(leadMeasurements);

                        //setGlobalMeasurements 总分析参数
                        ECGConversion.ECGGlobalMeasurements.GlobalMeasurements globalMeasurements = new ECGConversion.ECGGlobalMeasurements.GlobalMeasurements();
                        CurrentECG.GlobalMeasurements.getGlobalMeasurements(out globalMeasurements);
                        //ECGConversion.ECGGlobalMeasurements.GlobalMeasurements glob = new ECGConversion.ECGGlobalMeasurements.GlobalMeasurements();
                        globalMeasurements.Pdur = 120;
                        globalMeasurements.QTc = 220;
                        //12个 导联的信息 
                        //ECGConversion.ECGGlobalMeasurements. GlobalMeasurement[] gment=new ECGConversion.ECGGlobalMeasurements.GlobalMeasurement[12];
                        // glob.measurment = gment;
                        CurrentECG.GlobalMeasurements.setGlobalMeasurements(globalMeasurements);
                        CurrentECG.GlobalMeasurements.getGlobalMeasurements(out globalMeasurements);

                        ECGConversion.ECGDiagnostic.Statements stat;
                        CurrentECG.Diagnostics.getDiagnosticStatements(out stat);

                        int NrConfigItems = CurrentECG.Config.NrConfigItems;

                        ECGConversion.aECG.aECGFormat eCGFormat = (ECGConversion.aECG.aECGFormat)CurrentECG;

                        ECGConversion.aECG.aECGComponent aECGComponent = eCGFormat.Component;

                        //ECGConversion.aECG.aECGControlVariable[] controlVarible = eCGFormat.ControlVariables;


                        //这里设置 患者信息

                        //姓名
                        CurrentECG.Demographics.LastName = jsontmpre.Name;
                        //性别
                        if(jsontmpre.Sex == "男")
                        {
                            CurrentECG.Demographics.Gender = ECGConversion.ECGDemographics.Sex.Male;
                        }
                        else if(jsontmpre.Sex == "女")
                        {
                            CurrentECG.Demographics.Gender = ECGConversion.ECGDemographics.Sex.Female;
                        }
                        else
                        {
                            CurrentECG.Demographics.Gender = ECGConversion.ECGDemographics.Sex.Unspecified;
                        }
                        //身高
                        ushort height = (ushort)double.Parse(jsontmpre.Height);
                        CurrentECG.Demographics.setPatientHeight(height, ECGConversion.ECGDemographics.HeightDefinition.Millimeters);
                        //体重
                        ushort weight = (ushort)double.Parse(jsontmpre.Weight);
                        CurrentECG.Demographics.setPatientWeight(weight, ECGConversion.ECGDemographics.WeightDefinition.Kilogram);

                        //年龄
                        ushort age = ushort.Parse(jsontmpre.Age);
                        ECGConversion.ECGDemographics.AgeDefinition ageuint = ECGConversion.ECGDemographics.AgeDefinition.Unspecified;
                        if (jsontmpre.Ageuint == "岁")
                        {
                            //ageuint = ECGConversion.ECGDemographics.AgeDefinition.Years;
                            DateTime birthday = DateTime.Now.AddYears(0 - age);
                            CurrentECG.Demographics.setPatientAge(age, ECGConversion.ECGDemographics.AgeDefinition.Years);
                            CurrentECG.Demographics.PatientBirthDate = new ECGConversion.ECGDemographics.Date((ushort)birthday.Year, (byte)birthday.Month, (byte)birthday.Day);
                        }
                        else if (jsontmpre.Ageuint == "月")
                        {
                            DateTime birthday = DateTime.Now.AddMonths(0 - age);
                            CurrentECG.Demographics.setPatientAge(age, ECGConversion.ECGDemographics.AgeDefinition.Months);
                            CurrentECG.Demographics.PatientBirthDate = new ECGConversion.ECGDemographics.Date((ushort)birthday.Year, (byte)birthday.Month, (byte)birthday.Day);
                        }
                        else if (jsontmpre.Ageuint == "天")
                        {
                            DateTime birthday = DateTime.Now.AddDays(0 - age);
                            CurrentECG.Demographics.setPatientAge(age, ECGConversion.ECGDemographics.AgeDefinition.Days);
                            CurrentECG.Demographics.PatientBirthDate = new ECGConversion.ECGDemographics.Date((ushort)birthday.Year, (byte)birthday.Month, (byte)birthday.Day);
                        }
                        else if (jsontmpre.Ageuint == "周")
                        {
                            DateTime birthday = DateTime.Now.AddDays(0 - age * 7);
                            CurrentECG.Demographics.setPatientAge(age, ECGConversion.ECGDemographics.AgeDefinition.Days);
                            CurrentECG.Demographics.PatientBirthDate = new ECGConversion.ECGDemographics.Date((ushort)birthday.Year, (byte)birthday.Month, (byte)birthday.Day);
                        }
                        //测量时间
                        CurrentECG.Demographics.TimeAcquisition = DateTime.ParseExact(jsontmpre.SampleTime_Start, "yyyyMMddHHmmssFFFFF", System.Globalization.CultureInfo.InvariantCulture);
                        CurrentECG.Demographics.PatientID = DateTime.Now.ToString("yyyyMMddHHmmss-FFFFF");
                        //心电数据
                        //CurrentECG._Series[0].
                        IECGFormat writeFile = CurrentECG;

                        ECGWriter.Write(writeFile, dst, true);

                        if (writeFile != CurrentECG)
                            writeFile.Dispose();

                        if (ECGWriter.getLastError() != 0)
                        {
                            //MessageBox.Show(this, ECGWriter.getLastErrorMessage(), "Writing of file failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                    SetMessage("转换完成");
                    //MessageBox.Show("转换完成", "");
                    Application.Exit();
                    this.Close();
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    SetMessage("错误");
                    MessageBox.Show(ex.Message, "");
                    Application.Exit();
                    this.Close();
                }
            }
            else if (args.Length == 1)
            {

                string src = args[0];
                FileInfo file = new FileInfo(src);
                if (!file.Exists)
                {
                    SetMessage("文件不存在");
                    MessageBox.Show("文件不存在", "");
                    Application.Exit();
                    this.Close();
                }

                var jsontmpre = JsonHelper.DeserializeFileToObject<JsonFormat>(src);
                //string dst = src.Replace(".json", ".xml");
                string dst = jsontmpre.XMLPath;
                
                try
                {
                    IECGFormat CurrentECG = null;
                    UnknownECGReader _ECGReader = null;
                    if (new FileInfo(src).Exists)
                    {
                        int index = 0;
                        if (_ECGReader == null)
                        {
                            _ECGReader = new UnknownECGReader();
                        }
                        //
                        string curpath2 = System.Environment.CurrentDirectory + "\\Example.xml";
                        CurrentECG = _ECGReader.Read(curpath2);
                        int leadCount = jsontmpre.ChDatas.Count;
                        Signal[] _sign = new Signal[leadCount];
                        for (int i = 0; i < leadCount; i++)
                        {
                            _sign[i] = new Signal();
                            try
                            {
                                string leadname = jsontmpre.ChDatas[i].LeadName.Trim();// I、II、III……
                                // 导联类型
                                _sign[i].Type = (LeadType)(LeadType)ECGConverter.EnumParse(
                                     typeof(LeadType), leadname, true);
                                //导联数据 ，
                                string[] datastr = jsontmpre.ChDatas[i].digital.TrimEnd().Split(' ');
                                short[] shortArray = Array.ConvertAll<string, short>(datastr, delegate (string s) { return (short)(float.Parse(s) * 1000); });//.Skip(1).Take(5000).ToArray();
                                _sign[i].Rhythm = (short[])shortArray.Clone();
                                _sign[i].RhythmStart = 0;
                
                                _sign[i].RhythmEnd = shortArray.Length - 1;
                            }
                            catch (Exception e)
                            {
                                throw e;
                            }
                        }

                        Signals signals = new Signals();
                        CurrentECG.Signals.getSignals(out signals);

                        //采样率
                        signals.RhythmSamplesPerSecond = int.Parse(jsontmpre.Increament);
                        //增益 
                        signals.MedianAVM = int.Parse(jsontmpre.ChDatas[1].Sacle);
                        signals.RhythmAVM =1;  //修改信号增益幅值 ，
                        signals.SetLeads(_sign);
                        //CurrentECG.Signals.getSignals(out signals);
                        CurrentECG.Signals.setSignals(signals);

                        //在这里设置参数信息 
                        //setLeadMeasurements
                        //设置导联参数 
                        //LeadMeasurements leadMeasurements;
                        //CurrentECG.LeadMeasurements.getLeadMeasurements(out leadMeasurements);
                        //这里补充参数
                        //CurrentECG.LeadMeasurements.setLeadMeasurements(leadMeasurements);

                        //setGlobalMeasurements 总分析参数
                        //ECGConversion.ECGGlobalMeasurements.GlobalMeasurements globalMeasurements = new ECGConversion.ECGGlobalMeasurements.GlobalMeasurements();
                        //CurrentECG.GlobalMeasurements.getGlobalMeasurements(out globalMeasurements);
                        ////ECGConversion.ECGGlobalMeasurements.GlobalMeasurements glob = new ECGConversion.ECGGlobalMeasurements.GlobalMeasurements();
                        //globalMeasurements.Pdur = 120;
                        //globalMeasurements.QTc = 220;
                        ////12个 导联的信息 
                        ////ECGConversion.ECGGlobalMeasurements. GlobalMeasurement[] gment=new ECGConversion.ECGGlobalMeasurements.GlobalMeasurement[12];
                        //// glob.measurment = gment;
                        //CurrentECG.GlobalMeasurements.setGlobalMeasurements(globalMeasurements);
                        //CurrentECG.GlobalMeasurements.getGlobalMeasurements(out globalMeasurements);

                        ECGConversion.ECGDiagnostic.Statements stat;
                        CurrentECG.Diagnostics.getDiagnosticStatements(out stat);

                        int NrConfigItems = CurrentECG.Config.NrConfigItems;

                        ECGConversion.aECG.aECGFormat eCGFormat = (ECGConversion.aECG.aECGFormat)CurrentECG;

                        ECGConversion.aECG.aECGComponent aECGComponent = eCGFormat.Component;
                        ECGConversion.aECG.aECGSeries aecgseries = aECGComponent[0];
                        ECGConversion.aECG.aECGAnnotationSet[] aecgsets = aecgseries.Annotation;

                        ECGConversion.aECG.aECGAnnotation[] aECGAnnotations = aecgsets[0].Annotation;
                        //设置参数
                        for (int i=0;i< 20 ;i++)
                        {
                            ECGConversion.aECG.aECGAnnotation item = aECGAnnotations[0].Annotation[i];
                            if (item != null)
                            {

                                if (item.Code.Code == "MDC_ECG_TIME_PD_P")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", int.Parse(jsontmpre.P), "ms");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }

                                if (item.Code.Code == "MDC_ECG_TIME_PD_PR")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", int.Parse(jsontmpre.PR), "ms");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }

                                if (item.Code.Code == "MDC_ECG_TIME_PD_QRS")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", int.Parse(jsontmpre.QRS_Duration), "ms");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }

                                if (item.Code.Code == "MDC_ECG_TIME_PD_QT")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", int.Parse(jsontmpre.QTd_Duration), "ms");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }
                                if (item.Code.Code == "MDC_ECG_TIME_PD_QTc")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", int.Parse(jsontmpre.QTcd_Duration), "ms");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }

                                if (item.Code.Code == "MDC_ECG_ANGLE_P_FRONT")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", int.Parse(jsontmpre.P_deg), "deg");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }

                                if (item.Code.Code == "MDC_ECG_ANGLE_QRS_FRONT")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", int.Parse(jsontmpre.QRS_deg), "deg");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }

                                if (item.Code.Code == "MDC_ECG_ANGLE_T_FRONT")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", int.Parse(jsontmpre.T_deg), "deg");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }

                                if (item.Code.Code == "MDC_ECG_HEART_RATE")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", int.Parse(jsontmpre.HR), "bpm");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }
                                if (item.Code.Code == "MDC_ECG_WAVC_SV1")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", double.Parse(jsontmpre.SV1), "mv");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }

                                if (item.Code.Code == "MDC_ECG_WAVC_RV5")
                                {
                                    ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair("value", double.Parse(jsontmpre.RV5), "mv");
                                    pair.Type = "PQ";
                                    item.Value = pair;
                                }
                            }
                            
                        }
                        //滤波器参数
                        ECGConversion.aECG.aECGControlVariableHolder[] controlVaribleHolder = aecgseries.ControlVariables;



                        //这里设置 患者信息

                        //姓名
                        CurrentECG.Demographics.LastName = jsontmpre.Name;
                        //性别
                        if (jsontmpre.Sex == "男")
                        {
                            CurrentECG.Demographics.Gender = ECGConversion.ECGDemographics.Sex.Male;
                        }
                        else if (jsontmpre.Sex == "女")
                        {
                            CurrentECG.Demographics.Gender = ECGConversion.ECGDemographics.Sex.Female;
                        }
                        else
                        {
                            CurrentECG.Demographics.Gender = ECGConversion.ECGDemographics.Sex.Unspecified;
                        }
                        //身高
                        ushort height = (ushort)double.Parse(jsontmpre.Height);
                        CurrentECG.Demographics.setPatientHeight(height, ECGConversion.ECGDemographics.HeightDefinition.Millimeters);
                        //体重
                        ushort weight = (ushort)double.Parse(jsontmpre.Weight);
                        CurrentECG.Demographics.setPatientWeight(weight, ECGConversion.ECGDemographics.WeightDefinition.Kilogram);

                        //年龄
                        ushort age = ushort.Parse(jsontmpre.Age);
                        ECGConversion.ECGDemographics.AgeDefinition ageuint = ECGConversion.ECGDemographics.AgeDefinition.Unspecified;
                        if (jsontmpre.Ageuint == "岁")
                        {
                            //ageuint = ECGConversion.ECGDemographics.AgeDefinition.Years;
                            DateTime birthday = DateTime.Now.AddYears(0 - age);
                            CurrentECG.Demographics.setPatientAge(age, ECGConversion.ECGDemographics.AgeDefinition.Years);
                            CurrentECG.Demographics.PatientBirthDate = new ECGConversion.ECGDemographics.Date((ushort)birthday.Year, (byte)birthday.Month, (byte)birthday.Day);
                        }
                        else if (jsontmpre.Ageuint == "月")
                        {
                            DateTime birthday = DateTime.Now.AddMonths(0 - age);
                            CurrentECG.Demographics.setPatientAge(age, ECGConversion.ECGDemographics.AgeDefinition.Months);
                            CurrentECG.Demographics.PatientBirthDate = new ECGConversion.ECGDemographics.Date((ushort)birthday.Year, (byte)birthday.Month, (byte)birthday.Day);
                        }
                        else if (jsontmpre.Ageuint == "天")
                        {
                            DateTime birthday = DateTime.Now.AddDays(0 - age);
                            CurrentECG.Demographics.setPatientAge(age, ECGConversion.ECGDemographics.AgeDefinition.Days);
                            CurrentECG.Demographics.PatientBirthDate = new ECGConversion.ECGDemographics.Date((ushort)birthday.Year, (byte)birthday.Month, (byte)birthday.Day);
                        }
                        else if (jsontmpre.Ageuint == "周")
                        {
                            DateTime birthday = DateTime.Now.AddDays(0 - age * 7);
                            CurrentECG.Demographics.setPatientAge(age, ECGConversion.ECGDemographics.AgeDefinition.Days);
                            CurrentECG.Demographics.PatientBirthDate = new ECGConversion.ECGDemographics.Date((ushort)birthday.Year, (byte)birthday.Month, (byte)birthday.Day);
                        }
                        //测量时间
                        CurrentECG.Demographics.TimeAcquisition = DateTime.ParseExact(jsontmpre.SampleTime_Start, "yyyyMMddHHmmssFFFFF", System.Globalization.CultureInfo.InvariantCulture);
                        CurrentECG.Demographics.PatientID = jsontmpre.PId; //患者病例号

                        // ECGConversion.aECG.aECGSite aECGSite = eCGFormat.TestingSite;
                        ////清空无关信息
                        //aECGSite.Empty();
                        //心电数据
                        //CurrentECG._Series[0].
                        IECGFormat writeFile = CurrentECG;
                        ECGWriter.Write(writeFile, dst, true);

                        if (writeFile != CurrentECG)
                            writeFile.Dispose();

                        if (ECGWriter.getLastError() != 0)
                        {
                            //MessageBox.Show(this, ECGWriter.getLastErrorMessage(), "Writing of file failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                    //SetMessage("转换完成");
                    MessageBox.Show(dst +"文件保存成功！");
                    Application.Exit();
                    this.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    SetMessage("错误");
                    MessageBox.Show(ex.Message, "");
                    Application.Exit();
                    this.Close();
                }
                this.Close();
            }
            else
            {
                SetMessage("参数有误");
                MessageBox.Show("参数有误", "");
                Application.Exit();
                this.Close();
            }
        }


        public void SetMessage(string message)
        {
            lblInfo.Text = message;
        }

        public void SetNotifyInfo(int percent, string message)
        {
            this.lblInfo.Text = message;
            this.progressBar1.Value = percent;
        }

        public void SetNotifyInfo(int percent)
        {
            this.progressBar1.Value = percent;
        }

        private void ProgessFrm_Load(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            progressBar1.Maximum = 100;
        }
    }
}
